package sopt.dev.activity;

import java.io.File;
import java.util.Calendar;

import sopt.dev.R;
import sopt.dev.data.CityVO;
import sopt.dev.data.GagebuDataModel;
import sopt.dev.data.ItemVO;
import sopt.dev.network.CurrencyRateRequest;
import sopt.dev.network.NetworkController;
import sopt.dev.network.NetworkRequest;
import sopt.dev.network.NetworkRequest.OnProcessCompletedListener;
import sopt.dev.util.GagebuApp;
import sopt.dev.util.StringUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ExpenseAddActivity extends Activity implements OnClickListener {
	private final int ITEM_ADDRESS = 100;
	TextView tvDate, tvAddr;
	EditText edtName, edtExchange, edtPriceWon, edtComment;
	ImageView ivIcon;
	Button btnaddr;
	private CityVO<ItemVO> data;
	private ItemVO item;

	// image picker 변수
	private Uri mImageCaptureUri;
	private ImageView mImageView;

	private static final int PICK_FROM_CAMERA = 1;
	private static final int PICK_FROM_FILE = 2;

	// calender 변수
	private int year;
	private int month;
	private int day;
	private static final int DATE_DIALOG_ID = 1;
	private AlertDialog dialog;
	private AlertDialog.Builder builder;

	private Spinner currencySpinner;
	private Spinner nbbangSpinner;

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.expense_add_activity);

		ivIcon = (ImageView) findViewById(R.id.ex_add_iv_icon);
		ivIcon.setOnClickListener(this);

		tvDate = (TextView) findViewById(R.id.ex_add_tv_date);
		edtName = (EditText) findViewById(R.id.ex_add_et_name);
		edtExchange = (EditText) findViewById(R.id.ex_add_et_exchange);
		edtPriceWon = (EditText) findViewById(R.id.ex_add_et_price);
		edtComment = (EditText) findViewById(R.id.ex_add_et_memo);
		tvAddr = (TextView) findViewById(R.id.ex_add_tv_address);
		currencySpinner = (Spinner) findViewById(R.id.ex_add_spin_exchange);
		nbbangSpinner = (Spinner) findViewById(R.id.ex_add_spin_nbbang);

		item = getDataFromIntent();
		data = getCityDataFromIntent();

		// intent 로 부터 데이터를 받아들임
		if (item != null) {

			try {
				edtName.setText(item.getName());
				edtExchange.setText(String.valueOf(item.getPrice()));
				edtPriceWon.setText("");
				edtComment.setText(item.getComment());
			} catch (NullPointerException e) {
				e.printStackTrace();
			}
		}

		// 위치선택
		btnaddr = (Button) findViewById(R.id.ex_add_btn_address);
		btnaddr.setOnClickListener(this);

		/*
		 * 취소, 확인, 계속입력 버튼
		 */
		Button btnCel = (Button) findViewById(R.id.ex_add_btn_cel);
		btnCel.setOnClickListener(this);

		Button btnOk = (Button) findViewById(R.id.ex_add_btn_ok);
		btnOk.setOnClickListener(this);

		Button btnCon = (Button) findViewById(R.id.ex_add_btn_continue);
		btnCon.setOnClickListener(this);

		Button btnDate = (Button) findViewById(R.id.ex_add_btn_date);
		btnDate.setOnClickListener(this);

		// 날짜 초기화
		initCalendar();

		// spinner
		initSpinner();

		// imagepicker
		initImagePicker();

		// 환율계산
		// 사용자가 환율을 선택할 시
		currencySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				caculateCurrency();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		// 사용자가 인원 입력시
		nbbangSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				calculateNbbang();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
	}

	private void calculateNbbang() {
		// 선택된 인원수를 불러옴
		String selectedNbbang = nbbangSpinner.getSelectedItem().toString();
		String exchange = edtExchange.getText().toString();

		if (!selectedNbbang.equals("") && !exchange.equals("")) {

			// 입력된 price값 ;;중복되네염;;
			final double price = Double.parseDouble(exchange);
			// n빵 계산
			Double nbbangResult = price / Double.parseDouble(selectedNbbang);

			// 결과값
			edtPriceWon.setText(String.valueOf(nbbangResult));
		}

	}

	private void caculateCurrency() {
		// 선택된 환율을 불러옴
		String toCurrency = StringUtil.parseCurrency(currencySpinner
				.getSelectedItem().toString());

		try {
			final String krw = "KRW";

			// 선택된 환율을 한국돈으로 환율계산객체 생성
			CurrencyRateRequest currentRequest = new CurrencyRateRequest(krw,
					toCurrency);

			// 네트워크 컨트롤러에 스레드 객체 넘겨줌
			NetworkController.getInstance().enqueue(currentRequest);

			// 스레드 작업 완료시
			currentRequest
					.setOnCompleteListener(new OnProcessCompletedListener() {

						@Override
						public void onCompleted(NetworkRequest request) {

							try {
								// 환율 계산
								final Double currencyRate = (Double) request
										.getResult();
								// 입력 금액
								final double price = Double
										.parseDouble(edtExchange.getText()
												.toString());

								// UI 작업을 만들기 위한 처리
								new Thread(new Runnable() {
									@Override
									public void run() {
										runOnUiThread(new Runnable() {
											@Override
											public void run() {
												// 결과값 나타내줌
												edtPriceWon.setText(String
														.valueOf(price
																* currencyRate));
											}
										});
									}
								}).start();

							} catch (NumberFormatException e) {
								e.printStackTrace();
							}
						}
					});

		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	private ItemVO getDataFromIntent() {
		Intent i = getIntent();
		return (ItemVO) i.getParcelableExtra("item_data");
	}

	private CityVO<ItemVO> getCityDataFromIntent() {
		Intent i = getIntent();
		return (CityVO) i.getParcelableExtra("city_data");
	}

	private void initCalendar() {
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
	}

	private void initSpinner() {

		ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter
				.createFromResource(this, R.array.exchange_rate,
						android.R.layout.simple_spinner_item);

		arrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		Spinner spinner = (Spinner) findViewById(R.id.ex_add_spin_exchange);

		spinner.setAdapter(arrayAdapter);

		if (data != null) {
			int cityMoney = data.getCityMoney();

			spinner.setSelection(arrayAdapter.getPosition(String
					.valueOf(cityMoney)));
		}

		ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter
				.createFromResource(this, R.array.nbbang,
						android.R.layout.simple_spinner_item);

		arrayAdapter2
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		Spinner spinner2 = (Spinner) findViewById(R.id.ex_add_spin_nbbang);

		spinner2.setAdapter(arrayAdapter2);

		/*
		 * n빵 저장으로바꾸기 if (data != null) { String cityMoney =
		 * data.getCityMoney();
		 * 
		 * spinner2.setSelection(arrayAdapter2.getPosition(cityMoney)); }
		 */
	}

	private void initImagePicker() {
		final String[] items = new String[] { "From Camera", "From SD Card" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.select_dialog_item, items);

		builder = new AlertDialog.Builder(this);

		builder.setTitle("Select Image");
		builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				if (item == 0) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					File file = new File(Environment
							.getExternalStorageDirectory(), "tmp_avatar_"
							+ String.valueOf(System.currentTimeMillis())
							+ ".jpg");
					mImageCaptureUri = Uri.fromFile(file);

					try {
						intent.putExtra(
								android.provider.MediaStore.EXTRA_OUTPUT,
								mImageCaptureUri);
						intent.putExtra("return-data", true);

						startActivityForResult(intent, PICK_FROM_CAMERA);
					} catch (Exception e) {
						e.printStackTrace();
					}

					dialog.cancel();
				} else {
					Intent intent = new Intent();

					intent.setType("image/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);

					startActivityForResult(Intent.createChooser(intent,
							"Complete action using"), PICK_FROM_FILE);
				}
			}
		});

		mImageView = (ImageView) findViewById(R.id.ex_add_iv_photo);
		mImageView.setOnClickListener(this);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, year, month,
					day);

		}
		return null;
	}

	private void updateDisplay() {
		tvDate.setText(new StringBuilder()
				// Month is 0 based so add 1
				.append("날짜 : ").append(year).append("-").append(month + 1)
				.append("-").append(day).append(""));
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int myear, int monthOfYear,
				int dayOfMonth) {
			year = myear;
			month = monthOfYear;
			day = dayOfMonth;
			updateDisplay();
		}
	};

	/*
	 * imagePicker & crop from gallery
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Bitmap bitmap = null;
		String path = "";

		if (resultCode != RESULT_OK)
			return;
		
		switch (requestCode) {

		case PICK_FROM_CAMERA :
			// 여기왜 비어있찡..
			
			break;
			
		case PICK_FROM_FILE:
			if (requestCode == PICK_FROM_FILE) {
				mImageCaptureUri = data.getData();
				path = getRealPathFromURI(mImageCaptureUri); // from Gallery

				if (path == null)
					path = mImageCaptureUri.getPath(); // from File Manager

				if (path != null)
					bitmap = BitmapFactory.decodeFile(path);
			} else {
				path = mImageCaptureUri.getPath();
				bitmap = BitmapFactory.decodeFile(path);
			}

			mImageView.setImageBitmap(bitmap);
			
		case ITEM_ADDRESS:
			 if(resultCode == RESULT_OK) // Sub Activity의 결과 코드
			 {
			 // 받아온 주소를 표시한다.
			 tvAddr.setText(data.getStringExtra("addressText"));

			 }
		default:
			break;
		}

	}

	private String getRealPathFromURI(Uri contentUri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		@SuppressWarnings("deprecation")
		Cursor cursor = managedQuery(contentUri, proj, null, null, null);

		if (cursor == null)
			return null;

		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		cursor.moveToFirst();

		return cursor.getString(column_index);
	}

	public void saveData() {

		try {
			String cityName = data.getCityName();
			String itemName = edtName.getText().toString();
			String purchaseDate = tvDate.getText().toString().replace(":", "");
			Double itemPrice = Double.parseDouble(edtExchange.getText()
					.toString());
			String address = tvAddr.getText().toString();
			String comment = edtComment.getText().toString();

			ItemVO item = new ItemVO(cityName, itemName, purchaseDate, 0,
					itemPrice, " ", address, comment, 0);

			GagebuDataModel.getInstance().addItemData(cityName, item);

		} catch (NumberFormatException e) {
			Toast.makeText(GagebuApp.getContext(), "정보가 누락", Toast.LENGTH_SHORT);
			e.printStackTrace();
		} catch (NullPointerException e) {
			Toast.makeText(GagebuApp.getContext(), "정보가 누락", Toast.LENGTH_SHORT);
			e.printStackTrace();
		}

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.ex_add_btn_ok: {

			saveData();
			Intent i = new Intent(this, CityDetailActivity.class);
			i.putExtra("city_data", data);
			startActivity(i);
			finish();

			break;
		}

		case R.id.ex_add_btn_continue: {
			saveData();

			edtName.setText("");
			edtExchange.setText("");
			edtComment.setText("");
			tvDate.setText("");

			break;
		}

		case R.id.ex_add_btn_date: {
			showDialog(DATE_DIALOG_ID);
			break;
		}

		case R.id.ex_add_iv_photo: {
			dialog = builder.create();
			dialog.show();
			break;
		}
		case R.id.ex_add_btn_cel: {
			finish();
		}
		case R.id.ex_add_iv_icon: {
			// 다이얼로그 창 생성해서, 아이콘 선택 하도록?..
		}
		case R.id.ex_add_btn_address: {
			Intent i = new Intent(this, GoogleMapActivity.class);
			startActivityForResult(i, ITEM_ADDRESS);

		}

		}

	}

}